﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;

public partial class SystemManage_ContainerModelList : BasePage
{
    ISyContainerModelHandler modelManage = new SyContainerModelHandler();
    DataBase db = new DataBase();

    private static bool isUpdate = false;
    private static bool isDel = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1015"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    //判断用户有没有添加柜型权限
                    if (strPermission.Contains("1016"))
                    {
                        lblModelAdd.Visible = true;
                        lblImport.Visible = true;
                        Button2.Visible = true;
                    }
                    else
                    {
                        lblModelAdd.Visible = false;
                        lblImport.Visible = false;
                        Button2.Visible = false;
                    }
                    //判断用户有没有修改柜型权限
                    if (strPermission.Contains("1017"))
                    {
                        isUpdate = true;
                    }
                    else
                    {
                        isUpdate = false;
                    }
                    //判断用户有没有删除柜型权限
                    if (strPermission.Contains("1018"))
                    {
                        isDel = true;
                    }
                    else
                    {
                        isDel = false;
                    }

                }

              //  CheckPagePermission();//判断当前用户有没有添加删除更新的权限

            }           

            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "asc";
            dataBind();
        }
    }



    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        if (ViewState["Value"] != null)
        {
            list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
            if (ViewState["Name"].ToString() == "VolUpperLimit" || ViewState["Name"].ToString() == "VolLowerLimit")
            {
                sqlstr += " and " + ViewState["Name"].ToString() + "=@ColumnName";
            }
            else
            {
                sqlstr += " and " + ViewState["Name"].ToString() + " like '%' +  @ColumnName + '%'";
            }
        }
       
        if (ViewState["Status"] != null)
        {
            list.Add(new SqlParameter("@Status", ViewState["Status"].ToString()));
            sqlstr += " and Status = @Status";
        }
        parms = list.ToArray();
    }


    private void dataBind()
    {
        string sqlStr = "SELECT * FROM Sy_ContainerModel where 1=1 ";
        SqlParameter[] parms = new SqlParameter[4];
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = modelManage.GetModelList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvContainerModelList.DataSource = view;
        gvContainerModelList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    public string GetUserName(object id)
    {
        string name = string.Empty;
        IRolePurviewHandler usersManage = new RolePurviewHandler();
        UsersQuery query= usersManage.GetUsers(int.Parse(id.ToString()));
        if (query != null)
        {
            name = query.LoginID;            
        }
        return name;
    }
   

    protected void gvContainerModelList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvContainerModelList.PageIndex = e.NewPageIndex;
        dataBind();
    }
   
    protected void gvContainerModelList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvContainerModelList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtName.Text != string.Empty)
        {
            ViewState["Value"] = txtName.Text.Trim();
            ViewState["Name"] = ddlColumnName.SelectedValue;
        }
        else
        {
            ViewState["Value"] = null;
            ViewState["Name"] = null;
        }        

        if (radAll.Checked)
        {
            ViewState["Status"] = null;
        }
        else if (radYes.Checked)
        {
            ViewState["Status"] = "1";
        }
        else
        {
            ViewState["Status"] = "0";
        }
        dataBind();
    }
    protected void gvContainerModelList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Del")
        {
            if (!modelManage.ModelDelete(int.Parse(e.CommandArgument.ToString())))
            {
                Jscript.AlertInAjax(Resources.Messages.DeleteFailed, UpdatePanel1);
            }
        }
        dataBind();

    }

    protected void gvContainerModelList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton btnDel = (LinkButton)e.Row.FindControl("lbtnDel");
            Label lblEdit = (Label)e.Row.FindControl("lblEdit");

            if (isUpdate)
            {
                lblEdit.Visible = true;
            }
            else
            {
                lblEdit.Visible = false;
            }

            if (isDel)
            {
                btnDel.Visible = true;
            }
            else
            {
                btnDel.Visible = false;
            }
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvContainerModelList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvContainerModelList.PageCount)
            {
                this.gvContainerModelList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }

    #region
    /// <summary>
    /// 判断当前用户有没有输入的权限
    /// </summary>
    /// <returns></returns>
    public void CheckPagePermission()
    {
        StringBuilder sb = new StringBuilder();
        IRolePurviewHandler userManage = new RolePurviewHandler();
        UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
        if (query != null)
        {
            string roleIDs = query.Roles;
            if (roleIDs != string.Empty)
            {

                string strSql = "select * from Roles where RoleID in(" + roleIDs + ")";
                DataTable dtRoles = db.RunSql(strSql);
                if (dtRoles != null && dtRoles.Rows.Count > 0)
                {
                    for (int i = 0; i < dtRoles.Rows.Count; i++)
                    {
                        sb.Append(dtRoles.Rows[i]["RolePurview"].ToString() + ",");
                    }
                }

                string permission = sb.ToString();
                if (permission.Length > 0)
                {
                    permission = permission.Substring(0, permission.Length - 1);


                    //判断用户有没有添加柜型权限
                    if (permission.Contains("1016"))
                    {
                        lblModelAdd.Visible = true;
                    }
                    else
                    {
                        lblModelAdd.Visible = false;
                    }
                    //判断用户有没有修改柜型权限
                    if (permission.Contains("1017"))
                    {
                        isUpdate = true;
                    }
                    else
                    {
                        isUpdate = false;
                    }
                    //判断用户有没有删除柜型权限
                    if (permission.Contains("1018"))
                    {
                        isDel = true;
                    }
                    else
                    {
                        isDel = false;
                    }
                }
            }
        }

    }

    #endregion


    private DataTable Export()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Upper");
        dt.Columns.Add("Lower");
        dt.Columns.Add("Status");
        dt.Columns.Add("Remark");

        string sqlStr = "SELECT * FROM Sy_ContainerModel where 1=1 ";
        SqlParameter[] parms = new SqlParameter[4];
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dtM = modelManage.GetModelList(sqlStr, parms);
        if (dtM != null && dtM.Rows.Count > 0)
        {
            for (int i = 0; i < dtM.Rows.Count; i++)
            {
                dt.Rows.Add(new string[] {
                     dtM.Rows[i]["Model"].ToString(),
                       dtM.Rows[i]["VolUpperLimit"].ToString(),
                       dtM.Rows[i]["VolLowerLimit"].ToString(),
                       dtM.Rows[i]["Status"].ToString(),                           
                       dtM.Rows[i]["Remark"].ToString()                   
                      });
            }
        }
        return dt;

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        BackupToExcel.ExportExcel(Export(), "ContainerModel");
    }

}
